package mqtt

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commMqtt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Uuid"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEnv"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"go-fox-edge-kernel-manager/component"
	"strings"
	"time"
)

type mqttClient struct {
	client *commMqtt.MqttClient
}

func (e *mqttClient) GetDefaultHandler() mqtt.MessageHandler {
	return func(client mqtt.Client, msg mqtt.Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
	}
}

func (e *mqttClient) instance(router map[string]interface{}) {
	Handler.router = router

	// 获得系统配置参数
	configValue, err := component.ManageConfigService.GetConfigValueThis("mqttConfig")
	if err != nil {
		commLogger.Error("获取mqttConfig参数失败：" + err.Error())
		return
	}

	// 取出系统配置参数
	enable := Map.GetBool(configValue, "enable", false)
	mqtt := Map.GetMap(configValue, "mqtt", make(map[string]interface{}))
	topics := Map.GetMap(configValue, "topic", make(map[string]interface{}))

	if true != enable || mqtt == nil || topics == nil {
		return
	}

	clientId := Map.GetString(mqtt, "clientId", "")
	if clientId == "" {
		clientId = Uuid.RandomUUID()
	}

	request := Map.GetString(topics, "request", "")
	respond := Map.GetString(topics, "respond", "")
	if request == "" || respond == "" {
		return
	}

	request = strings.ReplaceAll(request, "{edgeId}", edgeEnv.GetCPUID())
	respond = strings.ReplaceAll(respond, "{edgeId}", edgeEnv.GetCPUID())

	// 设置MQTT的通信参数
	client := commMqtt.NewClient(clientId, mqtt)
	e.client = client

	// 向MQTT BROKER注册订阅topic
	Handler.clientId = clientId
	Handler.topic = respond
	e.client.Subscribe(request, Handler.Handler())

	// 开始连接
	go e.connect()
}

func (e *mqttClient) connect() {
	time.Sleep(3 * time.Second)
	for e.client.Connect() != nil {
		time.Sleep(3 * time.Second)
	}
}
